﻿Imports ACompany.OrderProcessing.Model
Imports ACompany.OrderProcessing.Services
Imports StructureMap

Public Class ProductsController
    Inherits System.Web.Mvc.Controller

    Private ProductService As IProductService

    Public Sub New()

    End Sub

    Public Sub New(ByVal ProductService As IProductService)
        Me.ProductService = ProductService
    End Sub

    Public Function Index()

        Dim Product As IList(Of Product) = ProductService.FindAll

        Return View("ProductList", Product)
    End Function

    Public Function Details(ByVal Id As String)

        Dim SelectedProductId As Guid = New Guid(Id)

        Dim Product As Product = ProductService.FindBy(SelectedProductId)

        Return View("ProductDetail", Product)
    End Function

    Public Function Edit(ByVal Id As String)
        Dim SelectedProductId As Guid = New Guid(Id)

        Dim Product As Product = ProductService.FindBy(SelectedProductId)

        Return View("ProductDetailEdit", Product)
    End Function

    <AcceptVerbs(HttpVerbs.Post)> _
   Public Function Edit(ByVal Id As String, ByVal formValues As FormCollection)

        Dim SelectedProductId As Guid = New Guid(Id)

        Dim Product As Product = ProductService.FindBy(SelectedProductId)

        Update(Product)

        If Product.GetBrokenRules.Count = 0 Then
            ProductService.Save(Product)
            ' Perform HTTP redirect to details page for the saved Product
            Return RedirectToAction("Details", New With {.id = Product.Id})
        Else
            ' Extension method
            ModelState.AddRuleViolations(Product.GetBrokenRules)

            Return View("ProductDetailEdit", Product)
        End If

    End Function

    Public Function Add()

        Dim newProduct As New Product

        Return View("ProductAdd", newProduct)

    End Function

    <AcceptVerbs(HttpVerbs.Post)> _
    Public Function Add(ByVal formValues As FormCollection)

        Dim newProduct As New Product

        Update(newProduct)

        If newProduct.GetBrokenRules.Count = 0 Then

            ProductService.Save(newProduct)
            Return RedirectToAction("Details", New With {.id = newProduct.Id.ToString})
        Else
            ' Extension method
            ModelState.AddRuleViolations(newProduct.GetBrokenRules)
            ' Rules broken
            Return View("ProductDetailEdit", newProduct)
        End If
    End Function

    Private Sub Update(ByVal Product As Product)

        With Product
            .Name = Request.Form("Name")
            .Price = ConvertStringToDouble(Request.Form("Price"))
            .Stock = ConvertStringToDouble(Request.Form("Stock"))
        End With

    End Sub
End Class
